package tags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.HashMap;
import java.util.Stack;

public final class PutTag extends TagSupport {

    private String name;
    private String attribute;
    private String page;

    public int doStartTag() throws JspException {
        InsertTag parent = (InsertTag)getAncestor("tags.InsertTag");
        if (parent==null) {
            throw new JspException("No Ancestor");
        }
        Stack temp_stack = parent.getStack();
        if (temp_stack==null) {
            throw new JspException("No Stack");
        }
        HashMap hashMap = (HashMap) temp_stack.peek();
        if (hashMap==null) {
            throw new JspException("No HashMap");
        }
        hashMap.put(name, page);
        return SKIP_BODY;
    }

    public void release() {
        name = attribute = page = null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    private TagSupport getAncestor(String className) throws JspException {
        Class klass = null;
        try {
            klass = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new JspException("Не найден класс" + e);
        }
        return (TagSupport) findAncestorWithClass(this, klass);
    }
}